﻿using System;
using System.Diagnostics;
using System.Text;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;

namespace Coding4Fun.MissionControl.WP.Network
{
    public class TcpSocketListener : SocketConnectorBase
    {
        StreamSocketListener coreSocket;

        public async void Start(int port)
        {
            coreSocket = new StreamSocketListener();
            coreSocket.ConnectionReceived += coreSocket_ConnectionReceived;

            try
            {
                await coreSocket.BindServiceNameAsync(port.ToString());
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                coreSocket.Dispose();
                coreSocket = null;

                OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = false, DeviceID = string.Empty });
            }
        }

        async void coreSocket_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Connection received!");

            DataReader reader = new DataReader(args.Socket.InputStream);

            try
            {
                while (true)
                {
                    StringBuilder builder = new StringBuilder();
                    uint actualLength = 1;

                    while (actualLength > 0)
                    {
                        actualLength = await reader.LoadAsync(256);
                        builder.Append(reader.ReadString(actualLength));
                    }

                    OnConnectionCompleted(new ConnectionEventArgs
                    {
                        Socket = args.Socket,
                        IsSuccessful = true,
                        DeviceID = args.Socket.Information.RemoteHostName.DisplayName,
                        Token = builder.ToString()
                    });
                    break;

                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
                OnConnectionCompleted(new ConnectionEventArgs { IsSuccessful = false });
            }
        }
    }
}

